package cjj.file;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashSet;
import java.util.Set;

/**
 * @author chenjunjie
 * @since 2018-06-04
 */
public class AppendFile {
    public static void main(String[] args) {
        AppendFile a = new AppendFile();
        String allSendCode =  a.read("E:\\jmeter\\sameText.txt");

    }

    public   void appendFile(String fileName, String content) {
        try {
            // 打开一个随机访问文件流，按读写方式
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
            // 文件长度，字节数
            long fileLength = randomFile.length();
            // 将写文件指针移到文件尾。
            randomFile.seek(fileLength);
            randomFile.writeBytes(content + "\r\n");
            randomFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取文件，并判断文件中是否有重复内容，如果有重复内容，把重复内容保存到另外一个文件
     * @param filePath
     * @return
     */
    private String read(String filePath) {
        BufferedReader br = null;
        String line = null;
        StringBuffer buf = new StringBuffer();
        Set set = new HashSet();

        try {
            br = new BufferedReader(new FileReader(filePath));
            int lineCount = 0;
            while ((line = br.readLine()) != null) {
                buf.append(line + "\r\n");
                lineCount = lineCount + 1;
                if(!set.add(line)){
                    AppendFile a = new AppendFile();
                    a.appendFile("E:\\jmeter\\sameTextRepeat.txt", line);

                }
                System.out.println(lineCount+":"+line);

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    br = null;
                }
            }
        }

        return buf.toString();
    }

}
